package file

import (
	"context"
	"strconv"

	"mall/service/attachment/rpc/internal/svc"
	"mall/service/attachment/rpc/internal/utils/errorhandler"
	"mall/service/attachment/rpc/types/attachment"
	"mall/service/backend/common/i18n"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendRestoreFileLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendRestoreFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendRestoreFileLogic {
	return &BackendRestoreFileLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendRestoreFileLogic) BackendRestoreFile(in *attachment.UUIDsReq) (*attachment.BaseResp, error) {
	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	for _, id := range in.Ids {
		if i, err := strconv.ParseInt(id, 10, 64); err == nil && i > 0 {
			err = l.svcCtx.MediaFile.Restore(l.ctx, tx, uint64(i))
			if err != nil {
				tx.Rollback()
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}
		}
	}

	tx.Commit()

	return &attachment.BaseResp{
		Msg: i18n.RestoreSuccess,
	}, nil
}
